use crate::chrono::{china_now, Datelike as _, STANDARD_DATETIME_FORMAT};
use crate::{
  chrono::now,
  cmd::Cmd,
  fs::{_fs::AutoPath as _, write_utf8},
};
use std::path::Path;

/// 包信息结构体
#[derive(Debug)]
pub struct PackageInfo {
  /// 包名
  pub name: String,
  /// 版本
  pub version: String,
  /// 描述
  pub description: String,
  /// 作者
  pub authors: String,
  /// 主页
  pub homepage: String,
  /// 仓库
  pub repository: String,
}

impl PackageInfo {
  /// 生成版本信息
  pub fn comments(&self) -> String {
    format!(
      "版本: {}\n主页: {}\n仓库: {}\n作者: {}",
      self.version,
      self.homepage,
      self.repository,
      self.formatted_authors()
    )
  }
  /// 生成版权信息
  pub fn copyright(&self) -> String {
    format!(
      "版权所有 © {} {}",
      chrono::Local::now().year(),
      if self.authors.is_empty() {
        String::new()
      } else {
        self.formatted_authors()
      }
    )
  }
  /// 格式化作者信息
  pub fn formatted_authors(&self) -> String {
    self.authors.replace(':', ", ")
  }
}

/// 导出git历史
pub fn export_git_history(
  pkg_version: impl AsRef<str>,
  target: impl AsRef<Path>,
  is_china: bool,
) -> crate::AnyResult<()> {
  target.as_ref().auto_remove_file()?;
  let build_time = if is_china {
    china_now()
      .ok_or("获取时间失败")?
      .format(STANDARD_DATETIME_FORMAT)
  } else {
    now().format(STANDARD_DATETIME_FORMAT)
  };
  let tag_commits = git_tag_commits().unwrap_or_default();
  let version_info = format!(
    "当前版本号: {}\n\
      构建时间: {}\n\
      构建类型: {}\n\
      历史提交 :\n\n{}",
    pkg_version.as_ref(),
    build_time,
    if cfg!(debug_assertions) {
      "Debug"
    } else {
      "Release"
    },
    tag_commits,
  );
  write_utf8(&target.as_ref().to_path_buf(), &version_info, false, false)?;

  Ok(())
}

/// 获取git标签提交历史
pub fn git_tag_commits() -> crate::Result<String> {
  // 获取所有标签的提交历史
  let tag_commits = Cmd::new("git")
    .args([
      "log",
      "--simplify-by-decoration", // 只显示有标签的提交
      "--date=\"format-local:%Y-%m-%d %H:%M:%S\"",
      "--format=\"标识: %h\n标签: %D\n时间: %cd\n作者: %an <%ae>\n提交: %s\n\"",
    ])
    .output()
    .map(|output| output.stdout.to_string())
    .unwrap_or("获取失败".to_string());

  Ok(tag_commits)
}
